﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;

/// <summary>
/// Сервис для получения списка сообщений для отображения
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class messagesService : System.Web.Services.WebService {

    private Dictionary<string, int> Messages;

    private Dictionary<string, int> DefaultMessages = new Dictionary<string, int>(){{"Hello, World!", 1}};

    public messagesService(string feedUrl)
    {
        if (string.IsNullOrEmpty(feedUrl))
        {
            Messages = DefaultMessages; //Тестовые данные
            return;
        }

        Messages = new Dictionary<string, int>();
        XmlDocument rssDoc = new XmlDocument();
        try
        {
            rssDoc.Load(new XmlTextReader(feedUrl));
            XmlNode rssNode = null;
            foreach (XmlNode node in rssDoc.ChildNodes)
            {
                if (node.Name.Equals("feed"))
                {
                    rssNode = node;
                    break;
                }
            }

            if (rssNode == null)
                return;

            foreach (XmlNode entryNode in rssNode.ChildNodes)
            {                
                if (!entryNode.Name.Equals("entry"))                
                    continue;
                
                foreach (XmlNode node in entryNode.ChildNodes)
                {
                    if (!node.Name.Equals("category"))
                        continue;
                    
                    string tag = node.Attributes["term"].Value;

                    if (!Messages.ContainsKey(tag))                    
                        Messages.Add(tag, 1);
                    else
                        Messages[tag] = Messages[tag] + 1;
                }
            }
        }
        catch
        {
            Messages = DefaultMessages; //Тестовые данные
        }
    }

    [WebMethod]    
    public XmlDocument GetMessages()
    {
        XmlDocument xmlMessages = new XmlDocument();

        if (Messages == null)
            return xmlMessages;

        int MinValue = int.MaxValue;
        int MaxValue = 0;

        xmlMessages.AppendChild(xmlMessages.CreateNode(XmlNodeType.Element, "mesasges", ""));
        
        for (int i = 0; i < Messages.Count; i++)
        {
            //генерируем xml тэг вида <message Text="Hello, World!" Weight="14" />
            XmlNode messageNode = xmlMessages.CreateNode(XmlNodeType.Element, "message", "");

            var attributeText = xmlMessages.CreateAttribute("Text");
            attributeText.Value = Messages.ElementAt(i).Key;
            messageNode.Attributes.Append(attributeText);

            var attributeWeight = xmlMessages.CreateAttribute("Weight");
            attributeWeight.Value = Messages.ElementAt(i).Value.ToString();
            messageNode.Attributes.Append(attributeWeight);

            if (Messages.ElementAt(i).Value < MinValue)
                MinValue = Messages.ElementAt(i).Value;

            if (Messages.ElementAt(i).Value > MaxValue)
                MaxValue = Messages.ElementAt(i).Value;

            xmlMessages.DocumentElement.AppendChild(messageNode);
        }

        XmlNode statisticsNode = xmlMessages.CreateNode(XmlNodeType.Element, "statistics", "");

        var attributeMinValue = xmlMessages.CreateAttribute("MinValue");
        attributeMinValue.Value = MinValue.ToString();
        statisticsNode.Attributes.Append(attributeMinValue);

        var attributeMaxValue = xmlMessages.CreateAttribute("MaxValue");
        attributeMaxValue.Value = MaxValue.ToString();
        statisticsNode.Attributes.Append(attributeMaxValue);

        xmlMessages.DocumentElement.PrependChild(statisticsNode);
        return xmlMessages;
    }
    
}

